package com.nbclass.controller;

import com.google.gson.Gson;
import com.nbclass.enums.SysConfigKey;
import com.nbclass.exception.OssException;
import com.nbclass.exception.UploadFileNotFoundException;
import com.nbclass.oss.OssFactory;
import com.nbclass.service.SysConfigService;
import com.nbclass.util.CoreConst;
import com.nbclass.util.MD5;
import com.nbclass.util.QiNiuYunUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.CloudStorageConfigVo;
import com.nbclass.vo.UploadResponse;
import com.nbclass.vo.base.ResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2018/1/31.
 */
@Controller
@RequestMapping("/upload")
public class UploadController{
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private SysConfigService sysConfigService;
    @ResponseBody
    @PostMapping(value = "/upload")
    public UploadResponse upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception{
        if (file == null || file.isEmpty()) {
            throw new UploadFileNotFoundException(UploadResponse.Error.FILENOTFOUND);
        }
        String originalFilename = file.getOriginalFilename();
        try {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String path = Objects.requireNonNull(OssFactory.init()).uploadSuffix(file.getBytes(), suffix,true);
            return  new UploadResponse(path,originalFilename, suffix, path, CoreConst.SUCCESS_CODE);
        } catch (OssException e) {
            return  new UploadResponse(originalFilename,  CoreConst.FAIL_CODE,e.getMessage());
        }catch (Exception e) {
            logger.error(String.format("UploadController.upload%s", e));
            throw e;
        }
    }
    @ResponseBody
    @PostMapping("/upload2QiniuForMd")
    public Object upload2QiniuForMd(@RequestParam("file") MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new UploadFileNotFoundException(UploadResponse.Error.FILENOTFOUND);
        }
        String originalFilename = file.getOriginalFilename();
        try {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String path = Objects.requireNonNull(OssFactory.init()).uploadSuffix(file.getBytes(), suffix,true);
            Map<String, Object> resultMap = new HashMap<>(3);
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功");
            resultMap.put("filename", path);
            return resultMap;
        } catch (OssException e) {
            return  new UploadResponse(originalFilename,  CoreConst.FAIL_CODE,e.getMessage());
        }catch (Exception e) {
            logger.error(String.format("UploadController.upload%s", e));
            throw e;
        }
    }

    @GetMapping(value = "/config")
    public String config(Model model){
        String value = sysConfigService.selectAll().get(SysConfigKey.CLOUD_STORAGE_CONFIG.getValue());
        Gson gson = new Gson();
        CloudStorageConfigVo cloudStorageConfig = gson.fromJson(value,CloudStorageConfigVo.class);
        model.addAttribute("cloudStorageConfig",cloudStorageConfig);
        return "upload/config";
    }

    @ResponseBody
    @PostMapping(value = "/saveConfig")
    public ResponseVo saveConfig(CloudStorageConfigVo cloudStorageConfig){
        Gson gson = new Gson();
        String value = gson.toJson(cloudStorageConfig);
        int a = sysConfigService.updateByKey(SysConfigKey.CLOUD_STORAGE_CONFIG.getValue(),value);
        if (a > 0) {
            return ResultUtil.success("云存储配置保存成功！");
        } else {
            return ResultUtil.error("云存储配置保存失败！");
        }

    }

}
